#!/usr/bin/env python
# coding=utf-8

# File Name: getURL.py
# Author: Bill Zhang
# Mail: zchcandid@gmail.com 
# Created Time: Fri 29 Nov 2013 04:10:49 PM CST
#mysql connector
import mysql.connector
from mysql.connector import errorcode
#import simplejson as json
import pika
#database name
def runUpdate(k):
    db=MysqlConnect("IDMAP")
    Mydb=db.cursor()
    Query2="SELECT a.`oid`,b.url FROM mapid a,mouser b WHERE a.CardCode='V00005' AND b.id=a.HQID\
     AND a.isUpdate=0 LIMIT %s,500" % 500
    Query3="SELECT a.`oid`,b.url FROM mapid a,digikey b WHERE a.CardCode='V00004' AND b.id=a.HQID\
     AND a.isUpdate=0 LIMIT %s,500" % 500
    Query=[0,0,Query2,Query3]
    Mydb.execute(Query[k])
    #get url from ecs_goods
    ids=[]
    for URL in Mydb:
        if not URL:
            print("ALL price has been update")
            return 666 
        if not URL[0]:
            continue
        url=URL[1].replace("www.mouser.cn","cn.mouser.com")
        message='{"ID":%s,"URL":"%s","k":%s}' %(int(URL[0]),url,k) 
        pushURL(message=message)
        ids.append(URL[0])
    setU="UPDATE mapid SET isUpdate=1 WHERE mapid.oid in %s;" % str(tuple(ids))
    Mydb.execute(setU)
    db.commit()
    Mydb.close()
    db.close()
    return 0

def pushURL(message):
    #push the messages to MQ
    parameters = pika.ConnectionParameters(host = '192.168.100.204' )
    connection = pika.BlockingConnection(parameters)
    channel = connection.channel()
    channel.queue_declare(queue = 'icmall' , durable = True )
    message =message
   # print("in libGetURL")
   # print(message)
    # make message persistent 
    channel.basic_publish(exchange = '', routing_key = 'icmall',body = message,properties=pika.BasicProperties(delivery_mode=2,))
   # print("The message has send")
    connection.close()
def MysqlConnect(DataBase):
    try:
         # cnx = mysql.connector.connect(user='root', password='123456',host='192.168.100.201',database=DataBase)
          cnx = mysql.connector.connect(user='admin001', password='admin001',host='192.168.100.204',database=DataBase)
    except mysql.connector.Error as err:
          if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
              print("Something is wrong with your user name or password")
          elif err.errno == errorcode.ER_BAD_DB_ERROR:
              print("Database does not exists")
          else:
              print(err)
    else:
        return cnx 
